from Global import Base,engine
from sqlalchemy.orm import sessionmaker
from Tables import Person

class PersonManagerService:
    def __init__(self):
        self.engine = engine

    def add_person(self, name, age, email):
        # 创建会话
        Session = sessionmaker(bind=self.engine)
        session = Session()
        # 创建用户
        person = Person(name=name, age=age, email=email)
        session.add(person)
        session.commit()

    def update_person(self, id, name, age, email):
        # 创建会话
        Session = sessionmaker(bind=self.engine)
        session = Session()
        # 查询用户
        person = session.query(Person).filter_by(id=id).first()
        # 更新用户
        person.name = name
        person.age = age
        person.email = email
        session.commit()

    def delete_person(self, id):
        # 创建会话
        Session = sessionmaker(bind=self.engine)
        session = Session()
        person = session.query(Person).filter_by(id=id).first()
        session.delete(person)
        session.commit()

    def show_persons(self):
        # 创建会话
        Session = sessionmaker(bind=self.engine)
        session = Session()
        # 查询用户
        persons = session.query(Person).all()
        for person in persons:
            print(person.id, person.name, person.age, person.email)

# 使用示例
# engine = create_engine('sqlite:///example.db')
# person_manager_service = PersonManagerService(engine)
# person_manager_service.add_person('John Doe', 24, 'john@example.com')
# person_manager_service.update_person(1, 'Jane Doe', 25, 'jane@example.com')
# person_manager_service.delete_person(1)
# person_manager_service.show_persons()
